package com.gljr.exam.web;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.gljr.exam.dao.ExamPaperQuestionRepository;
import com.gljr.exam.dao.UserRepository;
import com.gljr.exam.domain.ExamPaperQuestion;
import com.gljr.exam.tools.ExamUniTools;
import com.gljr.exam.web.form.ExamPaperForm;

@Controller
@SessionAttributes("user")
public class ExamPaperManagerController {

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private ExamPaperQuestionRepository examPaperQuestionRepository;

	@RequestMapping(path = "/alltopic", method = RequestMethod.GET)
	public String allTopic(@ModelAttribute ExamPaperForm form, Model model) {
		if (model.asMap().get("user") == null) {
			model.addAttribute("err", "您没有权限!");
			return "redirect:/errpagetips";
		}
		String currentUsername = ExamUniTools.getSessionUsername(model);
		boolean adminflag = userRepository.getIfAdmin(currentUsername);
		if (adminflag) {
			System.out.println("打印出是否为admin---->" + adminflag);
		} else {
			return "redirect:/errpage";
		}
		Long maxidlong = examPaperQuestionRepository.findMaxID();
		Map<String, String> map = new LinkedHashMap<String, String>();
		for (long i = 1; i <= maxidlong; i++) { // 试卷题目数量
			ExamPaperQuestion examPaperQuestion = examPaperQuestionRepository.findExquestionByExnum(i);
			String sLong = String.valueOf(i);
			map.put(sLong, examPaperQuestion.getExquestion());
		}
		for (Entry<String, String> entry : map.entrySet()) {// 迭代输出

			System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

		}

		model.addAttribute("arrMap", map);// 往freemarker传出map在前端显示
		return "alltopic";
	}

	@RequestMapping(path = "/alltopic", method = RequestMethod.POST)
	public String doAllTopic(@ModelAttribute ExamPaperForm form, Model model) {
		String sexnum = form.getExnum();
		Long exnum = Long.parseLong(sexnum);
		String exquestion = form.getExquestion();
		examPaperQuestionRepository.updateAllTopic(exnum, exquestion);
		return "redirect:/uploadsuccess";

	}

	@RequestMapping(path = "/admin", method = RequestMethod.GET)
	public String admin(Model model) {
		if (model.asMap().get("user") == null) {
			return "redirect:/errpagetips";
		}
		String currentUsername = ExamUniTools.getSessionUsername(model);
		boolean adminflag = userRepository.getIfAdmin(currentUsername);
		if (adminflag) {
			System.out.println("打印出是否为admin---->" + adminflag);
		} else {
			return "redirect:/errpage";
		}
		return "admin";

	}

}
